package com.push.common.utils;

import cn.hutool.core.text.TextSimilarity;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.py.Pinyin;
import com.hankcs.hanlp.dictionary.py.PinyinUtil;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.net.URLCodec;
import org.apache.http.HttpException;
import org.apache.http.util.EncodingUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;

public class URLUtil {
    /**
     * Checks if specified link is full URL.
     * @param link
     * @return True, if full URl, false otherwise.
     */
    public static boolean isFullUrl(String link) {
        if (link == null) {
            return false;
        }
        link = link.trim().toLowerCase();
        return link.startsWith("http://") || link.startsWith("https://") || link.startsWith("file://");
    }

    /**
     * Calculates full URL for specified page URL and link
     * which could be full, absolute or relative like there can
     * be found in A or IMG tags.
     */
    public static String fullUrl(String pageUrl, String link) {
        if ( isFullUrl(link) ) {
            return link;
        } else if ( link != null && link.startsWith("?") ) {
            int qindex = pageUrl.indexOf('?');
            int len = pageUrl.length();
            if (qindex < 0) {
                return pageUrl + link;
            } else if (qindex == len - 1) {
                return pageUrl.substring(0, len - 1) + link;
            } else {
                return pageUrl + "&" + link.substring(1);
            }
        }

        boolean isLinkAbsolute = link.startsWith("/");

        if ( !isFullUrl(pageUrl) ) {
            pageUrl = "http://" + pageUrl;
        }

        int slashIndex = isLinkAbsolute ? pageUrl.indexOf("/", 8) : pageUrl.lastIndexOf("/");
        if (slashIndex <= 8) {
            pageUrl += "/";
        } else {
            pageUrl = pageUrl.substring(0, slashIndex+1);
        }

        return isLinkAbsolute ? pageUrl + link.substring(1) : pageUrl + link;
    }


    public static String encodeUrl(String url, String charset) {
        if (url == null) {
            return "";
        }
        int index = url.indexOf("?");
        if (index >= 0) {
            try {
                String result = url.substring(0, index+1);
                String paramsPart = url.substring(index+1);
                StringTokenizer tokenizer = new StringTokenizer(paramsPart, "&");
                while (tokenizer.hasMoreTokens()) {
                    String definition = tokenizer.nextToken();
                    int eqIndex = definition.indexOf("=");
                    if (eqIndex >= 0) {
                        String paramName = definition.substring(0, eqIndex);
                        String paramValue = definition.substring(eqIndex + 1);
                        result += paramName + "=" + URLEncoder.encode(paramValue, charset) + "&";
                    } else {
                        result += URLEncoder.encode(definition, charset) + "&";
                    }
                }

                if( result.endsWith("&") ) {
                    result = result.substring(0, result.length() - 1);
                }

                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return url;
    }

    public static String decodeUrl(String escaped){
        System.out.println("escaped==="+escaped);
        String url = "";
        try {
            byte[] rawdata = URLCodec.decodeUrl(EncodingUtils.getAsciiBytes(escaped));
            url =  EncodingUtils.getString(rawdata, "UTF-8");
        } catch (DecoderException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static List<String> decodeUrl(List<String> escapeds){
        if (escapeds == null) {
            return escapeds;
        }
        List<String>  result = new ArrayList<>();
        for (String str : escapeds) {
            result.add(decodeUrl(str));
        }
        return result;
    }

    public static String encodeUrl(String url) {
        if (url == null) {
            return "";
        }
        int index = url.indexOf("?");
        if (index >= 0) {
            try {
                String result = url.substring(0, index+1);
                String paramsPart = url.substring(index+1);
                StringTokenizer tokenizer = new StringTokenizer(paramsPart, "&");
                while (tokenizer.hasMoreTokens()) {
                    String definition = tokenizer.nextToken();
                    int eqIndex = definition.indexOf("=");
                    if (eqIndex >= 0) {
                        String paramName = definition.substring(0, eqIndex);
                        String paramValue = definition.substring(eqIndex + 1);
                        result += paramName + "=" + URLEncoder.encode(paramValue, "UTF-8") + "&";
                    } else {
                        result += URLEncoder.encode(definition, "UTF-8") + "&";
                    }
                }

                if( result.endsWith("&") ) {
                    result = result.substring(0, result.length() - 1);
                }

                return result;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return url;
    }

    public static List<String> encodeUrl(List<String> urls, String charset) {
        if (urls == null) {
            return urls;
        }
        List<String>  result = new ArrayList<>();
        for (String str : urls) {
            result.add(encodeUrl(str, charset));
        }
        return result;
    }

    public static List<String> encodeUrl(List<String> urls) {
        if (urls == null) {
            return urls;
        }
        List<String>  result = new ArrayList<>();
        for (String str : urls) {
            result.add(encodeUrl(str, "UTF-8"));
        }
        return result;
    }

    public static String processEscapeXml(String s) {
        if (s != null) {
            StringBuffer result = new StringBuffer(s);
            int index = 0;
            for (int i = 0; i < s.length();) {
                char ch = s.charAt(i);
                if (ch == '&') {
                    String sub = s.substring(i);
                    if (sub.startsWith("&amp;")) {
                        result.replace(index, index+5, "&");
                        i += 5;
                    } else if (sub.startsWith("&apos;")) {
                        result.replace(index, index+6, "\'");
                        i += 6;
                    } else if (sub.startsWith("&gt;")) {
                        result.replace(index, index+4, ">");
                        i += 4;
                    } else if (sub.startsWith("&lt;")) {
                        result.replace(index, index+4, "<");
                        i += 4;
                    } else if (sub.startsWith("&quot;")){
                        result.replace(index, index+6, "\"");
                        i += 6;
                    } else if (sub.startsWith("&nbsp;")) {
                        result.replace(index, index+6, " ");
                        i += 6;
                    } else {
                        i++;
                    }
                } else {
                    i++;
                }
                index++;
            }
            return result.toString();
        }
        return null;
    }

    /**
     * 获取URL中的指定参数
     * @param url
     * @param keyWord
     * @return
     */
    public static String getOneParameter(String url,String keyWord) {
        String retValue = "";
        try {
            final String charset = "utf-8";
            url = URLDecoder.decode(url, charset);
            if (url.indexOf('?') != -1) {
                final String contents = url.substring(url.indexOf('?') + 1);
                String[] keyValues = contents.split("&");
                for (int i = 0; i < keyValues.length; i++) {
                    String key = keyValues[i].substring(0, keyValues[i].indexOf("="));
                    String value = keyValues[i].substring(keyValues[i].indexOf("=") + 1);
                    if (key.equals(keyWord)) {
                        if (value != null || !"".equals(value.trim())) {
                            retValue = value;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retValue;
    }

    public static void main(String[] args) {

    }
}
